'use strict'

import * as bodyParser from "body-parser";
import * as express from "express";
import * as cors from 'cors';
import * as path from 'path';
import * as http from 'http';
import userRouter from './routes/user';
import InitMysql from './model/index';
import { db_conf } from './config/config.mysql'
import HandleAuth from "./middleware/auth";
export default class Server {

    public static app: express.Express;

    constructor() { }

    public static async initializeApp(): Promise<http.Server> {
        try {
            Server.app = express();

            Server.initApp();

            Server.initStaticPath();

            Server.initMiddelware();

            Server.initRouter();

            Server.initTempalte();

            try {
                await Server.initDatabase();
            } catch (_) {
                console.error("Failed to init database", _);
            }

            return Server.app.listen(Server.app.get("port"));
        } catch (_) {
            throw new Error('server running failed');
        }

    }

    private static initDatabase() {
        /**
         * @esc tips：
         * [path.resolve(__dirname, './model/user/*.model.ts')]
         * 使用这种模式，必须保证model 是 default 模式导出
         */
        new InitMysql(db_conf, [path.resolve(__dirname, './model/**/*.model.ts')]);
        // other db instance ...
    }

    private static initApp() {
        Server.app.set("port", process.env.PORT || 4399);
        Server.app.use(cors());
        Server.app.use(bodyParser.json());
        Server.app.use(bodyParser.urlencoded({ extended: false }));
    }

    private static initMiddelware() {
        Server.app.use('/user', HandleAuth.checkedToken);
    }

    private static initRouter() {
        Server.app.get("/", (_req, res) => { res.send("server is running!") });
        Server.app.use('/ejs_test', (_req, res) => { res.send('index') })
        Server.app.use('/user', userRouter);
        Server.app.use((_req, res) => { res.json({ code: 404, data: [], message: '404 not found!' }) })
    }

    private static initStaticPath() {
        const env = process.env.NODE_ENV
        if (env !== 'development' && env !== 'production') throw new Error('NODE_ENV setting fail!')
        if (env == 'development') {
            Server.app.use(express.static(path.join(__dirname, './front')));
            return;
        }
        Server.app.use(express.static('./front'));
    }

    private static initTempalte() {
        Server.app.set('views', path.join(__dirname, 'views'));
        Server.app.set('view engine', 'ejs');
    }
}

